package cn.dankal.lequ.ui.fragment.download_fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.dankal.lequ.R;
import cn.dankal.lequ.commom.adapter.BaseAdapter.ViewHolder;
import cn.dankal.lequ.commom.adapter.BaseAdapter.recyclerview.CommonAdapter;
import cn.dankal.lequ.domain.download.CommonUtils;
import cn.dankal.lequ.domain.download.DownLoadInfo;
import cn.dankal.lequ.domain.download.DownloadManager;
import cn.dankal.lequ.domain.download.FileUtils;

/**
 * Created by Dankal on 16/4/21.
 */
public class DownloadingFragment extends Fragment implements DownloadManager.DownLoadObserver {
    @Bind(R.id.recyclerview)
    RecyclerView rv_compre;
    LinearLayoutManager linearLayoutManager;

    private Handler handler = new Handler();

    //apk地址
    private String apkUrl = "http://imtt.dd.qq.com/16891/C841EDE441D29005FA508F793FFACBBC.apk?fsname=com.qq.ac.android_6.2.7_87.apk";
    private DownloadManager dm;
    private List<DownLoadInfo> mDatas;
    private CommonAdapter<DownLoadInfo> commonAdapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recyclerview, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initDownload();
        initRecyclerView();
        getAPKinfo();
    }

    /**
     * 获取正在下载的apk信息(创建测试数据)
     * 添加到list
     * 通知adapter
     */
    private void getAPKinfo() {
        for (int i = 0; i < 4; i++) {
            DownLoadInfo apk = new DownLoadInfo();
            apk.packageName = "apk" + new Date().getTime();
            apk.savePath = FileUtils.getDownloadPath();
            apk.state = DownloadManager.STATE_UNDOWNLOAD;
            apk.url = apkUrl;
            apk.task = dm.new DownLoadTask(apk);
            mDatas.add(apk);
        }
        commonAdapter.notifyDataSetChanged();
    }

    private void initDownload() {
        dm = DownloadManager.getInstance();
        dm.addObserver(this);
    }

    /**
     * 初始化recyclerView
     * 创建adapter
     * 添加点击事件
     */
    private void initRecyclerView() {
        linearLayoutManager = new LinearLayoutManager(getActivity());
        rv_compre.setLayoutManager(linearLayoutManager);
        rv_compre.setHasFixedSize(true);
        mDatas = new ArrayList<>();

        //获取下载位置
        //TODO 开始下载
        //TODO 暂停
        commonAdapter = new CommonAdapter<DownLoadInfo>(getActivity(), R.layout.item_currency_download, mDatas) {
            @Override
            public void convert(final ViewHolder holder, final DownLoadInfo info) {
                String cur = new BigDecimal(info.curProgress).divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP).doubleValue() + "MB";

                holder.setImageResource(R.id.iv_download_game_icon, R.mipmap.wushen);
                holder.setText(R.id.tv_download_game_name, "武神赵子龙——林允儿代言");
                holder.setText(R.id.tv_download_game_version, "版本 1.12 ➡ 1.55");
                holder.setText(R.id.tv_download_game_traffic, cur + "MB/" + info.maxProgress + "MB");
                holder.setTag(R.id.tv_download_game_apk, holder.getView(R.id.tv_download_game_traffic));

                //给下载按钮添加点击事件
                holder.setOnClickListener(R.id.tv_download_game_apk, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        info.view = v;
                        /**
                         * 根据下载的不同状态 进行不同的步骤
                         */
                        switch (info.state) {
                            //下载完成后 点击按钮进行安装
                            case DownloadManager.STATE_DOWNLOADED:
                                mDatas.remove(info);
                                notifyDataSetChanged();
                                break;
                            //下载失败  则重试
                            case DownloadManager.STATE_DOWNLOADFAILED:
                                dm.downLoad(info);
                                break;
                            //正在下载  则暂停下载
                            case DownloadManager.STATE_DOWNLOADING:
                                info.state = DownloadManager.STATE_PAUSEDOWNLOAD;
                                break;
                            //已安装
                            case DownloadManager.STATE_INSTALLED:
                                mDatas.remove(info);
                                notifyDataSetChanged();
                                break;
                            //下载暂停  则继续下载
                            case DownloadManager.STATE_PAUSEDOWNLOAD:
//                                new Thread(info.task).start();
                                dm.downLoad(info);

                                break;
                            //未下载  则开始下载
                            case DownloadManager.STATE_UNDOWNLOAD:
                                Log.i("down123", "STATE_UNDOWNLOAD begin to download");
//                                new Thread(info.task).start();
                                dm.downLoad(info);
                                break;
                            case DownloadManager.STATE_WAITINGDOWNLOAD:
                                break;
                        }

                    }
                });
            }
        };
        rv_compre.setAdapter(commonAdapter);
    }


    /**
     * 下载状态发生改变
     *
     * @param info
     */
    @Override
    public void onDownLoadInfoChange(final DownLoadInfo info) {

        handler.post(new Runnable() {
            @Override
            public void run() {

                TextView dBtn = null;
                TextView progress = null;
                String cur = null;
                switch (info.state) {
                    case DownloadManager.STATE_DOWNLOADED:
                        cur = new BigDecimal(info.curProgress).divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP).doubleValue() + "MB";
                        dBtn = (TextView) info.view;
                        progress = (TextView) dBtn.getTag();
                        progress.setText(cur + "/" + info.maxProgress + "MB");
                        dBtn.setText("完成");

                        FragmentActivity activity = getActivity();
                        if (activity != null)
                            CommonUtils.installApp(activity,
                                    new File(info.savePath, info.packageName + ".apk"));
                        break;
                    case DownloadManager.STATE_DOWNLOADFAILED:
                        dBtn = (TextView) info.view;
                        progress = (TextView) dBtn.getTag();
                        progress.setText("下载失败，请重试");
                        dBtn.setText("重新");
                        break;
                    case DownloadManager.STATE_DOWNLOADING:
                        cur = new BigDecimal(info.curProgress).divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP).doubleValue() + "MB";

                        dBtn = (TextView) info.view;
                        progress = (TextView) dBtn.getTag();
                        progress.setText(cur + "/" + info.maxProgress + "MB");
                        dBtn.setText("暂停");
                        break;
                    case DownloadManager.STATE_INSTALLED:
                        break;
                    case DownloadManager.STATE_PAUSEDOWNLOAD:
                        cur = new BigDecimal(info.curProgress).divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP).doubleValue() + "MB";

                        dBtn = (TextView) info.view;
                        progress = (TextView) dBtn.getTag();
                        progress.setText(cur + "/" + info.maxProgress + "MB" + " 已暂停");
                        dBtn.setText("继续");
                        break;
                    case DownloadManager.STATE_UNDOWNLOAD:
                        break;
                    case DownloadManager.STATE_WAITINGDOWNLOAD:
                        break;
                }
            }
        });
    }
}
